package com.sctvcloud.renhe.ui.activities;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.db.DBUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.CustomFragmentChangeHelper;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomFrameLayout;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Cache;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.base.BaseCanPlayActivity;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.AttitudesBean;
import com.sctvcloud.renhe.beans.ChatItem;
import com.sctvcloud.renhe.beans.FLive;
import com.sctvcloud.renhe.beans.FLiveDy;
import com.sctvcloud.renhe.beans.FSubscribe;
import com.sctvcloud.renhe.beans.FUsers;
import com.sctvcloud.renhe.beans.LiveInfo;
import com.sctvcloud.renhe.beans.NewsClickBean;
import com.sctvcloud.renhe.beans.SingleResult;
import com.sctvcloud.renhe.http.AbsNetCallBack;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.http.ParamsEditor;
import com.sctvcloud.renhe.push.IMsgRecieve;
import com.sctvcloud.renhe.push.MyJPushReceiver;
import com.sctvcloud.renhe.ui.adapter.holder.LiveRoomDynamicHolder;
import com.sctvcloud.renhe.ui.dialog.ShowDiaFragment;
import com.sctvcloud.renhe.ui.fragment.ChatRoomFragment;
import com.sctvcloud.renhe.ui.fragment.LiveRoomFragment;
import com.sctvcloud.renhe.ui.fragment.LivingChildFragment;
import com.sctvcloud.renhe.ui.utils.BarrageScreenController;
import com.sctvcloud.renhe.ui.utils.GlideUtil;
import com.sctvcloud.renhe.ui.utils.IBarrageControll;
import com.sctvcloud.renhe.ui.utils.NotificationsUtils;
import com.sctvcloud.renhe.ui.utils.OnFullClick;
import com.sctvcloud.renhe.ui.utils.SkipUtil;
import com.sctvcloud.renhe.ui.utils.TitleUtils;
import com.sctvcloud.renhe.ui.utils.UIUtils;
import com.sctvcloud.renhe.ui.widget.BarragePlayerView;
import com.sctvcloud.renhe.ui.widget.BasePlayerView;
import com.sctvcloud.renhe.utils.ListTypeUtils;
import com.sctvcloud.renhe.utils.ResultAsyncTask;
import com.sctvcloud.renhe.utils.UserManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 直播详情页
 */
public class LivingActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.OnRefreshListener, CanRefreshLayout.IScrollView, IBarrageControll
        , LivingChildFragment.OnNetCallback, LiveRoomDynamicHolder.OnImageClickListener, IMsgRecieve, BarragePlayerView.OnSendComment {

    public static final String ADVANCE_TYPE = "advance_type";
    public static final String ADVANCE_TITLE = "advance_title";
    public static final String ADVANCE_IMAGE_URL = "advance_image_url";
    public static final String ADVANCE_START_TIME = "advance_start_time";

    //    @BindView(R.id.living_refresh)
//    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomFrameLayout container;
    @BindView(R.id.living_lay_tab)
    protected ViewGroup layTab;
    @BindView(R.id.living_lay_intro)
    protected ViewGroup layIntro;
    @BindView(R.id.title_top_layout)
    protected ViewGroup layTitle;
    @BindView(R.id.living_ac_base)
    protected ViewGroup baseLay;
    @BindView(R.id.living_img_video)
    protected CustomEXImageView topImg;
    @BindView(R.id.living_tx_intro)
    protected CustomFontTextView intro;
    @BindView(R.id.living_sec_date)
    protected CustomFontTextView date;
    @BindView(R.id.living_sec_source)
    protected CustomFontTextView liveSource;
    @BindView(R.id.living_sec_click_count)
    protected CustomFontTextView liveClickCount;//点击量
    @BindView(R.id.living_sub)
    protected Button subscribeLiving;//点击预约

    @BindView(R.id.living_tab_room_living)
    protected CustomFontTextView tabLive;
    @BindView(R.id.living_tab_room_chat)
    protected CustomFontTextView tabChat;
    @BindView(R.id.living_top_mode)
    protected CustomFontTextView livtTag;
    @BindView(R.id.living_sec_toggle)
    protected CustomCheckBox introToggle;
    @BindView(R.id.living_scroll_child)
    protected LinearLayoutCompat linear;
    @BindView(R.id.living_video_container)
    protected AbsoluteLayout videoContainer;
    @BindView(R.id.living_img_play)
    protected ImageView img;
    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView share;
    @BindView(R.id.title_top_logo_layout)
    protected LinearLayout title_top_logo_layout;
    @BindView(R.id.live_advance_layout)
    protected LinearLayout advanceLayout;
    @BindView(R.id.living_count_down)
    protected CustomFontTextView countDownTime;
    @BindView(R.id.comment_layout_doup)
    protected CustomFontTextView commentDoup;
    @BindView(R.id.chat_room_comment_layout)
    protected LinearLayout commentLayout;
    private AttitudesBean attitudes;
    private CountDownTimer advanceDownTimer;
    private LiveRoomFragment liveRoomFragment;
    private ChatRoomFragment chatRoomFragment;
    private CustomFragmentChangeHelper<LivingChildFragment> fragmentChangeHelper;

    private Handler handler;

    private boolean hasSelectRoom;
    /**
     * 是否是直播,此属性暂时只在设置测试数据是使用
     */
    private boolean isTempLiving;

    private BarrageScreenController screenController;

    private BarrageTestAsync barrageTestAsync;
    private FLive mFLive;
    private boolean mIsLoading = false;
    private String mUrl;
    private String liveUrl;
    private int mSelectedIndex = 0;

    private String topImgUrl;

    private boolean isFirstPlay = true;

    private boolean isPlayFromRoom;

    private int verOffset;
    /**
     * 聊天室视频播放的时长记录
     */
    private int roomPlayedPos;

    private Gson gson;

    private BarragePlayerView videoPlayer;

    private FLiveDy otherVideoTemp;

    private int mainVideoPos;

    private String RECEIVE_TAG = "com.sctvcloud.renhe.NOTIFICATION";
    private Calendar calendar;
    private String month, day, hour, minute;

    private boolean isPlayingWhenPause;
    private boolean isFromACResult;//是否是从指定的activity返回的
    ArrayList<Pair<String, String>> pairsParent = new ArrayList<>();
    HashMap<String, String> param;
    private String baseConstUrl;
    private boolean isAdvance = false;//是直播预告
    private String news24Domain = "";//市州新闻静态请求路径的域名
    private boolean isCityState = false;
    private boolean isFirstLoad = true;
    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        private int[] ii = new int[2];
        private int oldY;
        int c;

        @Override
        public void onGlobalLayout() {
            container.getLocationInWindow(ii);
//            JLog.e("eeae  "+container.getY()+"   "+ii[1]+"   "+container.getPivotY());
            if (isPlayFromRoom && floatVideoUtils.isShowing()) {
                c = ii[1] - oldY;
                if (c != 0) {
                    ViewGroup.LayoutParams lp = videoContainer.getLayoutParams();
                    lp.height -= c;
                    videoContainer.setLayoutParams(lp);
                }
            }
            oldY = ii[1];
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        title_top_logo_layout.setVisibility(View.GONE);
        new TitleUtils(this);
        this.setTypeName(1);//设置日志统计中的类型
        isCityState = getIntent().getBooleanExtra(Constances.IS_CITY_STATE, false);
        mUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        if (isCityState) {
            //泸州新闻动态接口域名
            baseConstUrl = Cache.getInstance().getChoosedCityStUrl();//Constances.LZ_BASE_URL;
            String news24Url = Cache.getInstance().getChoosedCityNewsUrl();
            news24Domain = UIUtils.getDomain(news24Url);
            share.setVisibility(View.GONE);
        } else {
            news24Domain = "";
        }
        topImgUrl = getIntent().getStringExtra(BaseActivity.EX_DATA);
        param = (HashMap<String, String>) getIntent().getSerializableExtra("TAG");
        if (param != null) {
            pairsParent = new ArrayList<>();
            Iterator<HashMap.Entry<String, String>> it = param.entrySet().iterator();
            while (it.hasNext()) {
                HashMap.Entry<String, String> entry = it.next();
                pairsParent.add(new Pair<String, String>(entry.getKey(), entry.getValue()));
            }
        }
        isVideoTop = false;
        isAdvance = getIntent().getBooleanExtra(LivingActivity.ADVANCE_TYPE, false);
        if (isAdvance) {
            checkNotificationPermission();
            subscribeLiving.setVisibility(View.VISIBLE);
//            liveSource.setVisibility(View.GONE);
            liveClickCount.setVisibility(View.GONE);
            createdPlayerView();
//            layTab.setVisibility(View.GONE);
//            container.setVisibility(View.GONE);
            advanceLayout.setVisibility(View.VISIBLE);
            String title = getIntent().getStringExtra(LivingActivity.ADVANCE_TITLE);
            String topImg = getIntent().getStringExtra(LivingActivity.ADVANCE_IMAGE_URL);
            String startTime = getIntent().getStringExtra(LivingActivity.ADVANCE_START_TIME);
            if (videoPlayer != null && videoPlayer.getThumbImge() != null) {
                GlideUtil.getGlideWithLarge169DefNotFit(this, topImg).into(videoPlayer.getThumbImge());
            }
            SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.PATTERN_IN);
            Date date = null;
            String downTime = "";
            try {
                date = formatter.parse(startTime);
                if (date.getTime() > 0) {
                    final long time = date.getTime();
                    downTime = DateUtils.timeLater(time);
                    countDownTime.setText(setNumColor("距离直播还有" + downTime));
                    long down = time - System.currentTimeMillis();
                    advanceDownTimer = new CountDownTimer(down, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            String d = DateUtils.timeLater(time);
                            countDownTime.setText(setNumColor("距离直播还有" + d));
                        }

                        @Override
                        public void onFinish() {
                            isAdvance = false;
                            subscribeLiving.setVisibility(View.GONE);
                            liveClickCount.setVisibility(View.VISIBLE);
                            advanceLayout.setVisibility(View.GONE);
                            layTab.setVisibility(View.VISIBLE);
                            container.setVisibility(View.VISIBLE);
                            initLivingView();
                            refreshData();
//                            mRefreshLayout.autoRefresh();
                        }
                    }.start();
                } else {
                    countDownTime.setText(setNumColor("距离直播还有" + startTime));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//            mIsLoading = true;
//            getData();
            refreshData();
        } else {
            subscribeLiving.setVisibility(View.GONE);
            advanceLayout.setVisibility(View.GONE);
//            liveSource.setVisibility(View.VISIBLE);
            liveClickCount.setVisibility(View.VISIBLE);
            layTab.setVisibility(View.VISIBLE);
            container.setVisibility(View.VISIBLE);
            refreshData();
        }
        initLivingView();
    }

    private void initLivingView() {
        if (TextUtils.isEmpty(mUrl)) {
            toast(R.string.loading_invalid_data);
            finish();
            return;
        }

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                msgHandler(msg);
            }
        };
        isTempLiving = getIntent().getBooleanExtra("liveTest", false);
        fragmentChangeHelper = new CustomFragmentChangeHelper<>(R.id.can_content_view);
        layTab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (layTab.getHeight() > 0) {
//                    if (hasSelectRoom) {
//                        ViewGroup.LayoutParams lp = appBarLayout.getLayoutParams();
//                        lp.height = layTab.getHeight();
//                        appBarLayout.setLayoutParams(lp);
                    layTab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    } else {
//                        selectTab(tabLive, tabChat);
//                    }
//                    tabLive.callOnClick();
                }
            }
        });
        if (!TextUtils.isEmpty(topImgUrl)) {
            GlideUtil.loadImgLarge169Def(this, topImgUrl, topImg);
        }
        container.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
//        mRefreshLayout.setOnLoadMoreListener(this);
//        mRefreshLayout.setOnRefreshListener(this);
//        mRefreshLayout.setLoadMoreEnabled(false);
        container.setiScrollView(this);
//        getData();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_living);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        JLog.e("bbab   from ac "+isFromACResult+"   isPlaying  "+isPlayingWhenPause);
        if (isFromACResult && isPlayingWhenPause) {
            if (floatVideoUtils != null) {
                if (floatVideoUtils.isShowing()) {
                    if (mainVideoPos > 0) {
                        floatVideoUtils.getPlayerView().setPlayPosition(mainVideoPos);
                    }
                    if (NetModeUtil.GetNetype(this) == 1) {
                        floatVideoUtils.startPlay();
                    }
                }
            }
        }
        if (null != videoPlayer) {
            videoPlayer.setMute(videoPlayer.isMute());
        }
    }


    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
    }

    /**
     * 从全屏返回
     *
     * @param newConfig
     */
    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);

        //避免GSYBaseVideoPlayer类中的设置隐藏虚拟键的干扰。
        videoPlayer.setHideKey(false);
//        //显示虚拟按键
//        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
//            //低版本sdk
//            View v =  getWindow().getDecorView();
//            v.setSystemUiVisibility(View.VISIBLE);
//        } else if (Build.VERSION.SDK_INT >= 19) {
//            View decorView = getWindow().getDecorView();
//            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
//            decorView.setSystemUiVisibility(uiOptions);
//        }
        getWindow().getDecorView().setSystemUiVisibility(0);
    }

    private void refreshData() {
        isFirstLoad = true;
        if (mIsLoading) {
//            mRefreshLayout.refreshComplete();
            return;
        }
        mIsLoading = true;
        if (mFLive == null || mFLive.getLiveInfo() == null) {
            getData();
            return;
        }
        if (mSelectedIndex == 0) {
            liveRoomFragment.onRefresh();
        } else if (mSelectedIndex == 1) {
            chatRoomFragment.onRefresh();
        }

    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
//            mRefreshLayout.refreshComplete();
            return;
        }
        JLog.e("zzaz ok  live=" + mFLive + "   select index=" + mSelectedIndex);
        mIsLoading = true;
        if (mFLive == null || mFLive.getLiveInfo() == null) {
            getData();
            return;
        }
        if (mSelectedIndex == 0) {
            liveRoomFragment.onRefresh();
        } else if (mSelectedIndex == 1) {
            chatRoomFragment.onRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        mIsLoading = true;

        if (mSelectedIndex == 0) {
            if (liveRoomFragment != null) {
                liveRoomFragment.onLoadMore();
            }
        } else if (mSelectedIndex == 1) {
            if (chatRoomFragment != null) {
                chatRoomFragment.onLoadMore();
            }

        }
        //  }
    }


    /**
     * 请求当前直播的相关数据
     */
    private void getData() {
        NetUtils.getNetAdapter().getLiveInfo(getOwnerName(), mUrl, new AbsNetCallBack<FLive>(FLive.class) {
            @Override
            public void onSuc(FLive fLive) {
                if (fLive == null || fLive.getLiveInfo() == null) {
                    onError(null, null);
                    return;
                }
                if (isAdvance) {
                    //直播预告是初始化内容
//                    initAdvanceInfo(fLive);
                    checkIsSubscribe(fLive);
                }
                FLive live = mFLive;
                if (initInfo(fLive)) {
                    boolean should = true;
                    if (live != null) {
                        if (live.getLiveInfo() != null) {
                            if (!TextUtils.equals(live.getLiveInfo().getLiveId(), fLive.getLiveInfo().getLiveId())) {
                                deltJpushTag(live.getLiveInfo().getLiveId());
                            } else {
                                should = false;
                            }
                        }
                    }
                    if (should) {
                        setJPushTag(fLive.getLiveInfo().getLiveId());
                    }
                    if (fragmentChangeHelper != null && fragmentChangeHelper.getShowingFragment() != null) {
                        fragmentChangeHelper.getShowingFragment().setBaseLiveId(fLive.getLiveInfo().getLiveId());
                        fragmentChangeHelper.getShowingFragment().setLiving(fLive.getLiveInfo().isLiving());
                        fragmentChangeHelper.getShowingFragment().onRefresh();
                    } else {
                        tabClick(tabLive);
                    }
                }
                //TODO 测试自动添加评论
//                startAdService(handler1);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                img.setVisibility(View.GONE);
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish(false);
                isFirstLoad = false;
            }
        });
    }

    private boolean isSubscribe = false;

    private void checkIsSubscribe(final FLive fLive) {
        List<FSubscribe> dbListData = getDbListData();
        final LiveInfo liveInfo = fLive.getLiveInfo();
        if (null != liveInfo) {
            String liveId = liveInfo.getLiveId();
            if (null != dbListData) {
                for (FSubscribe subscribe : dbListData) {
                    if (liveId.equals(subscribe.getLiveId())) {
                        isSubscribe = true;
                        break;
                    }
                }
            }
            if (isSubscribe) {
                subscribeLiving.setText("已预约");
                subscribeLiving.setBackground(getResources().getDrawable(R.drawable.bg_subscribe_bt_gray));
            } else {
                subscribeLiving.setText("预约");
                subscribeLiving.setBackground(getResources().getDrawable(R.drawable.bg_subscribe_bt_red));
            }
            subscribeLiving.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isSubscribe) {
                        deleteSubscribe(liveInfo);
                        stopAlarm(liveInfo.getLiveId(), liveInfo.getLiveTitle(), liveInfo.getLiveUrl());

                    } else {
                        if (NotificationsUtils.isNotificationEnabled(LivingActivity.this)) {
                            if (!TextUtils.isEmpty(liveInfo.getLiveUrl()) && !TextUtils.isEmpty(liveInfo.getLiveTime())) {
                                setSubscribeList(liveInfo);
                                setAlarm(liveInfo.getLiveId(), liveInfo.getLiveTitle(), liveInfo.getLiveUrl(), liveInfo);
                            } else {
                                toast("直播地址或者预约时间为空不能进行预约");
                                return;
                            }
                        } else {
                            showDialog();
                            return;
                        }

                    }
                    isSubscribe = !isSubscribe;
                    if (isSubscribe) {
                        subscribeLiving.setText("已预约");
                        subscribeLiving.setBackground(getResources().getDrawable(R.drawable.bg_subscribe_bt_gray));
                    } else {
                        subscribeLiving.setText("预约");
                        subscribeLiving.setBackground(getResources().getDrawable(R.drawable.bg_subscribe_bt_red));
                    }
                }
            });
        }
    }

    /**
     * 极光推送-删除标签
     *
     * @param tag
     */
    private void deltJpushTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        JLog.e("MyJPushReceiver    will del tag::" + tag);
        HashSet<String> set = new HashSet<>();
        set.add(tag);
        JPushInterface.deleteTags(this, 1, set);
    }

    /**
     * 极光推送-设置标签
     *
     * @param tag
     */
    private void setJPushTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        JLog.e("MyJPushReceiver    set tag::" + tag);
        HashSet<String> set = new HashSet<>();
        set.add(tag);
        JPushInterface.addTags(this, 1, set);
    }

    @Override
    protected void onPause() {
        isPlayingWhenPause = floatVideoUtils != null && floatVideoUtils.isPlaying();
        if (isPlayingWhenPause) {
            mainVideoPos = floatVideoUtils.getPlayerView().getCurrentPositionWhenPlaying();
        }
        super.onPause();
    }


    @OnClick(value = {R.id.title_top_layout_edit, R.id.title_top_layout_back})
    public void shareClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_edit:
                if (mFLive != null && mFLive.getLiveInfo() != null && !TextUtils.isEmpty(mFLive.getLiveInfo().getSharedUrl())) {
                    this.setNewsId(mFLive.getLiveInfo().getLiveId());
                    showShareFragment(mFLive.getLiveInfo(), new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {
                            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                            pairs.addAll(pairsParent);
                            pairs.add(pair);
                            GridsumWebDissector.getInstance().trackEvent(LivingActivity.this, "", mFLive.getLiveInfo().getLiveTitle(), "", 200, pairs);

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
            case R.id.title_top_layout_back:
                finish();
                break;
        }

    }

    @Override
    protected void onDestroy() {
        MyJPushReceiver.setMsgRecieve(null);
        if (null != RHTask) {
            RHTask.cancel();
            RHTask = null;
        }
        if (null != readyOnlineTimer) {
            readyOnlineTimer.cancel();
            readyOnlineTimer.purge();
            readyOnlineTimer = null;
        }
        if (container != null) {
            container.setiScrollView(null);
            container.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
        }
//        if (mRefreshLayout != null) {
//            mRefreshLayout.setOnLoadMoreListener(null);
//            mRefreshLayout.setOnRefreshListener(null);
//        }
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
        if (mFLive != null) {
            if (mFLive.getLiveInfo() != null) {
                deltJpushTag(mFLive.getLiveInfo().getLiveId());
            }
        }
        super.onDestroy();
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
    }

    @Override
    protected void onLoginSuc() {
        super.onLoginSuc();
        if (loginMode == Constances.MODE_COMMENT_SEND_COMMENT || loginMode == Constances.MODE_COMMENT_SEND_NEWS) {
            if (commentDiaFragment != null && commentDiaFragment.isResumed()) {
                commentDiaFragment.onLoginSuc();
            }
        }
    }

    @NonNull
    @Override
    protected BasePlayerView createdPlayerView() {
        if (videoPlayer == null) {
//            JLog.e("ppip  will create videoplayer");
            videoPlayer = new BarragePlayerView(this);
//            videoPlayer.setHasBarrage(true);
//            videoPlayer.setBarrageOpen(true);
            videoPlayer.setLiving(true);
            videoPlayer.setSendListener(this);

            videoPlayer.setFullClick(new OnFullClick() {
                @Override
                public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
                    JLog.e("vvav  full click isLandScape=" + isLandscape + "   player=" + player);
                    onFullClicked(player, isLandscape);
                }
            });

        }

        return videoPlayer;
    }

//
//    protected void onFullClicked(StandardGSYVideoPlayer player, boolean isLandscape) {
//        if (player == null || TextUtils.isEmpty(player.getOriUrl())) {
//            if (isDataGetting()) {
//                toast(R.string.loading_data_wait);
//            } else {
//                toast(R.string.data_wrong);
//            }
//            return;
//        }
//        if (isLandscape) {
//            if (orientationUtils != null) {
//                orientationUtils.backToProtVideo();
//            } else {
//                actionToPortrait();
//            }
//            StandardGSYVideoPlayer.backFromWindowFull(LivingActivity.this);
//        } else {
//            if (orientationUtils != null) {
//                orientationUtils.resolveByClick();
//            } else {
//                JLog.e("vvav   will to Landscape");
//                //判断视频源是横屏还是竖屏的，弱势竖屏的，就不转向
//                if (player.getWidthToHeightRatio() == 0 || player.getWidthToHeightRatio() > 1) {
//                    //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
//                    actionToLandscape();//在这切换为横屏
//                }
//            }
//
//            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
//            //      player = (BasePlayerView) player.startWindowFullscreen(LivingActivity.this, false, true);
//
//            if (player != null) {
//                player.getBackButton().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        JLog.e("vvav  will back press");
//                        onBackPressed();
//                    }
//                });
//            }
//        }
//    }


    @Override
    public StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayer;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        JLog.e("bbab  request="+requestCode+"   result="+resultCode+"   data="+data+"  "+otherVideoTemp);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            isFromACResult = true;
            if (otherVideoTemp == null || data == null) {
                return;
            }
            if (resultCode == RESULT_OK) {
                otherVideoTemp.setPlayedPos(0);
            } else {
                int pos = data.getIntExtra(SkipUtil.EX_POS, 0);
//                JLog.e("bbab result pos="+pos);
                otherVideoTemp.setPlayedPos(pos);
            }
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
//        JLog.e("event=" + motionEvent + "\ncontainer=" + container + "\n" + fragmentChangeHelper);
        if (container == null) {
            return false;
        }
//        JLog.e("ssd  " + verOffset + "   " + r);
        if (verOffset > 0) {
            return true;
        }
        if (ViewUtils.isTouchPointInView(container, motionEvent.getRawX(), motionEvent.getRawY(), 0)
                && fragmentChangeHelper != null) {
            if (fragmentChangeHelper.getShowingFragment() != null) {
                return fragmentChangeHelper.getShowingFragment().canScrollUp(motionEvent);
            }
        }
        return false;
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        if (container == null) {
            return false;
        }
        if (ViewUtils.isTouchPointInView(container, motionEvent.getRawX(), motionEvent.getRawY(), 0)
                && fragmentChangeHelper != null) {
            if (fragmentChangeHelper.getShowingFragment() != null) {
                return fragmentChangeHelper.getShowingFragment().canScrollDown(motionEvent);
            }
        }
        return false;
    }

    @Override
    protected void onChangeToPlaying() {
        openBarrage();
    }

    @Override
    protected void onChangeToStop() {
        closeBarrage();
    }

    @Override
    public void openOrCloseBarrage(boolean isOpen) {
        if (isOpen) {
            openBarrage();
        } else {
            closeBarrage();
        }
    }

    @OnClick({R.id.chat_room_comment, R.id.comment_layout_doup})
    protected void commentClick(View v) {
        if (v.getId() == R.id.chat_room_comment) {
            //点击评论时，先切换到聊天室
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.addAll(pairsParent);
            pairs.add(new Pair<>("行为类型", "点击"));
            selectTab(tabChat, tabLive);
            GridsumWebDissector.getInstance().trackEvent(this, "", "聊天室", "", 200, pairs);
            if (chatRoomFragment == null) {
                chatRoomFragment = new ChatRoomFragment();
                if (isCityState) {
                    //是由泸州新闻进入
                    chatRoomFragment.setCityShow(true);
                }
                if (mFLive != null && mFLive.getLiveInfo() != null) {
                    chatRoomFragment.setLiving(mFLive.getLiveInfo().isLiving());
                    chatRoomFragment.setBaseLiveId(mFLive.getLiveInfo().getLiveId());
                }
            }
            fragmentChangeHelper.showFragment(chatRoomFragment, getSupportFragmentManager(), 1);
            mSelectedIndex = 1;
            if (floatVideoUtils != null && isPlayFromRoom) {
                floatVideoUtils.stopVideoView(false);
            }

            //再进行评论
            if (TextUtils.isEmpty(baseConstUrl)) {
                showCommentDialog(mFLive.getLiveInfo().getLiveId(), null, Constances.COMMENT_TYPE_LIVE);
            } else {
                showCommentDialog(mFLive.getLiveInfo().getLiveId(), true, null, Constances.COMMENT_TYPE_LIVE);
            }
        } else if (v.getId() == R.id.comment_layout_doup) {
            liveDoUp();
        }
    }

    /**
     * 直播点赞
     */
    private void liveDoUp() {
        if (mFLive != null && mFLive.getLiveInfo() != null) {
            final String liveId = mFLive.getLiveInfo().getLiveId();
            if (UserManager.isLoginS()) {
                commentDoup.setDrawableEnlarge();

                ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
                pe.put("dynamicId", liveId);
                pe.put("fType", 4);//1 主播 2报料 3新闻 4 直播 5视频
//        pe.put("token", UserManager.getInstance().getToken());
                pe.put("userId", UserManager.getInstance().getUser().getUserId());

                NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult.isSuccess()) {
                            SkipUtil.skipToAddUserOperate(LivingActivity.this, getOwnerName(), 13, 1, "直播点赞/取消点赞", liveId, Cache.getInstance().getCurrentChannelId());
                            if (null != attitudes) {
                                if (attitudes.isDigg()) {
                                    attitudes.setDigg(!attitudes.isDigg());
                                    attitudes.setAttitudesCount(attitudes.getAttitudesCount() - 1);
                                } else {
                                    attitudes.setDigg(!attitudes.isDigg());
                                    attitudes.setAttitudesCount(attitudes.getAttitudesCount() + 1);
                                }

                                if (attitudes.isDigg()) {
                                    Drawable drawable = LivingActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                    commentDoup.setDrawables(drawable, null, null, null);
                                    commentDoup.setTextColor(LivingActivity.this.getResources().getColor(R.color.colorTxRedMain_));
                                } else {
                                    Drawable drawable = LivingActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                    commentDoup.setDrawables(drawable, null, null, null);
                                    commentDoup.setTextColor(LivingActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                                }
                                commentDoup.setText("" + attitudes.getAttitudesCount());
                                if (attitudes.isDigg()) {
                                    addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                    }
                });

            } else {
                toLogin();
            }
        }
    }

    /**
     * 获取直播点赞
     */
    private void getAttitudes(final String liveId) {
        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", liveId);
        pe.put("fType", 4);//1 主播 2报料 3新闻(短视频) 4 直播
//        pe.put("token", UserManager.getInstance().getToken());
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            pe.put("userId", user.getUserId());
        } else {
            pe.put("userId", "");
        }
        NetUtils.getNetAdapter().getAttitudes(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<AttitudesBean>(AttitudesBean.class) {
            @Override
            public void onSuc(AttitudesBean attitudesBean) {
                if (null != attitudesBean) {
                    attitudes = attitudesBean;
                    if (attitudesBean.isDigg()) {
                        Drawable drawable = LivingActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        commentDoup.setDrawables(drawable, null, null, null);
                        commentDoup.setTextColor(LivingActivity.this.getResources().getColor(R.color.colorTxRedMain_));
                    } else {
                        Drawable drawable = LivingActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        commentDoup.setDrawables(drawable, null, null, null);
                        commentDoup.setTextColor(LivingActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                    }
                    commentDoup.setText("" + attitudesBean.getAttitudesCount());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
    }

    @Override
    public void onNetPrepare(LivingChildFragment fragment, int mode) {
        if (null != fragment) {
            if (null != chatRoomFragment && fragment == chatRoomFragment) {
//                if (mode == ChatRoomFragment.MODE_COMMENT) {
//                    if (TextUtils.isEmpty(baseConstUrl)) {
//                        showCommentDialog(mFLive.getLiveInfo().getLiveId(), null, Constances.COMMENT_TYPE_LIVE);
//                    } else {
//                        showCommentDialog(mFLive.getLiveInfo().getLiveId(), true, null, Constances.COMMENT_TYPE_LIVE);
//                    }
//
//                }
            } else if (null != liveRoomFragment && fragment == liveRoomFragment) {
                if (mode == LivingChildFragment.MODE_PLAY) {
                    if (isPlayFromRoom && floatVideoUtils != null && roomPlayedPos > 0) {
                        floatVideoUtils.startPlay();
                    }
                }
            }
        }
    }

    @Override
    public void onNetEnd(LivingChildFragment fragment, int mode, boolean canLoadMore) {
        if (mode == LivingChildFragment.MODE_PLAY) {
            if (fragment == liveRoomFragment) {
                if (isPlayFromRoom && floatVideoUtils != null && floatVideoUtils.isPlaying()) {
                    roomPlayedPos = 1;
                    floatVideoUtils.stopVideoView(false);
                } else {
                    roomPlayedPos = 0;
                }
            }
        } else {
//            onNetFinish(canLoadMore);
        }
    }

    @Override
    public void doOther(LivingChildFragment fragment, int mode, Object obj, Object obj2) {
        if (fragment == liveRoomFragment) {
            if (mode == LivingChildFragment.MODE_PLAY) {
                if (obj instanceof FLiveDy) {
                    FLiveDy fld = (FLiveDy) obj;
                    if (fld == null || TextUtils.isEmpty(fld.getDyVideoUrl())) {
                        toast(R.string.data_wrong);
                    } else {
//                        playVideo((View) obj2, , false, true);s
                        otherVideoTemp = fld;
                        SkipUtil.skipToVideoPlay(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, fld.getDyVideoUrl()), fld.getPlayedPos(), 0);
                    }
                }
            }
        }
    }

    @Override
    protected boolean isShouldMuteStart() {
        return !isPlayFromRoom && isFirstPlay && NetModeUtil.GetNetype(this) == 1;
    }

    @Override
    public void onRecylerScroll(int dx, int dy) {
        if (isPlayFromRoom && floatVideoUtils != null) {
//            floatVideoUtils.scrollBy(dx, dy);
            floatVideoUtils.recyclerScrolled(dx, dy);
        }
    }

    @OnCheckedChanged(R.id.living_sec_toggle)
    public void toggleChange(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            layIntro.setVisibility(View.VISIBLE);
            introToggle.setText(R.string.collapse_intro);
        } else {
            layIntro.setVisibility(View.GONE);
            introToggle.setText(R.string.expande_intro);
        }
        if (isPlayFromRoom) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isPlayFromRoom) {
                        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
//                        mlp.topMargin = linear.getHeight() - container.getHeight() + layTitle.getHeight();
                        mlp.height = container.getHeight();
                        videoContainer.setLayoutParams(mlp);
                    }
                }
            }, 100);
        }
    }

    @OnClick({R.id.living_tab_room_living, R.id.living_tab_room_chat})
    public synchronized void tabClick(View view) {
//        handler.sendEmptyMessageDelayed(1,500);
//        if (mIsLoading) {
//            return;
//        }
//        clickTemp = false;
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//        pairs.add(new Pair<>("页面", "直播"));
        pairs.addAll(pairsParent);
        pairs.add(new Pair<>("行为类型", "点击"));
        int id = view.getId();
        if (id == R.id.living_tab_room_living) {
            selectTab(tabLive, tabChat);
            GridsumWebDissector.getInstance().trackEvent(this, "", "直播间", "", 200, pairs);
            if (liveRoomFragment == null) {
                liveRoomFragment = new LiveRoomFragment();
                liveRoomFragment.setBaseUrl(mUrl);
                if (!TextUtils.isEmpty(baseConstUrl)) {
                    //是由泸州新闻进入
                    liveRoomFragment.setCityShow(true);
                }
                if (mFLive != null && mFLive.getLiveInfo() != null) {
//                    clickTemp = liveRoomFragment.setLiveInfo(mFLive.getLiveInfo());
//                    liveRoomFragment.setDatas(mFLive.getChannel(), LivingChildFragment.MODE_NORMAL);
                    liveRoomFragment.setLiving(mFLive.getLiveInfo().isLiving());
                    liveRoomFragment.setBaseLiveId(mFLive.getLiveInfo().getLiveId());
                }
            }
            fragmentChangeHelper.showFragment(liveRoomFragment, getSupportFragmentManager(), 0);
            mSelectedIndex = 0;
        } else if (id == R.id.living_tab_room_chat) {
            selectTab(tabChat, tabLive);
            GridsumWebDissector.getInstance().trackEvent(this, "", "聊天室", "", 200, pairs);
            if (chatRoomFragment == null) {
                chatRoomFragment = new ChatRoomFragment();
                if (isCityState) {
                    //是由泸州新闻进入
                    chatRoomFragment.setCityShow(true);
                }
                if (mFLive != null && mFLive.getLiveInfo() != null) {
                    chatRoomFragment.setLiving(mFLive.getLiveInfo().isLiving());
                    chatRoomFragment.setBaseLiveId(mFLive.getLiveInfo().getLiveId());
                }
            }
            fragmentChangeHelper.showFragment(chatRoomFragment, getSupportFragmentManager(), 1);
            mSelectedIndex = 1;
            if (floatVideoUtils != null && isPlayFromRoom) {
                floatVideoUtils.stopVideoView(false);
            }
        }

//        checkCanLoadMore();
    }

    private void checkCanLoadMore() {
//        if (mSelectedIndex == 0) {
//            mRefreshLayout.setLoadMoreEnabled(liveRoomFragment.canLoadMore());
//        } else if (mSelectedIndex == 1) {
//            mRefreshLayout.setLoadMoreEnabled(chatRoomFragment.canLoadMore());
//        }
    }

    @OnClick(R.id.living_img_play)
    public void click(View view) {
        if (mFLive == null || TextUtils.isEmpty(mFLive.getLiveInfo().getLiveUrl())) {
//            toast("数据错误");
            return;
        }
        playVideo(topImg, mFLive.getLiveInfo().getLiveUrl(), mFLive.getLiveInfo().isLiving(), false);
    }


    private void openBarrage() {
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
        barrageTestAsync = new BarrageTestAsync();
        barrageTestAsync.ex();
    }

    private void closeBarrage() {
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
    }

    /**
     * 加载直播数据源URL
     *
     * @param refer
     * @param url
     * @param isLiving
     * @param isFromRoom
     */
    private void playVideo(final View refer, final String url, final boolean isLiving, final boolean isFromRoom) {
//        AbsoluteLayout container = videoContainer;
//        if (isFromRoom) {
//            isLiving = false;
//            container = videoRoomContainer;
//        }
        VideoInfo videoInfo = new VideoInfo("");
        if (initFloatVideoUtils(refer, videoContainer, 0, videoInfo)) {
//            bottomController.initInfo(liveInfo);
            floatVideoUtils.showPlayer(refer, false);
        } else {
            floatVideoUtils.stopVideoView(false);
        }
        if (videoPlayer != null && videoPlayer.getThumbImge() != null) {
            GlideUtil.getGlideWithLarge169DefNotFit(this, topImgUrl).into(videoPlayer.getThumbImge());
        }
        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
        int oh = 0;
        if (isFromRoom) {
//            mlp.topMargin = topImg.getHeight() + layTitle.getHeight() - verOffset;
            oh = linear.getHeight() - container.getHeight() + layTitle.getHeight();
            mlp.height = container.getHeight();
//            JLog.e("will set height  "+ mlp.height);
        } else {
            roomPlayedPos = 0;
            mlp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        }
        floatVideoUtils.setOtherHeight(oh);
        videoContainer.setLayoutParams(mlp);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                floatVideoUtils.setLiving(isLiving);
                floatVideoUtils.showPlayer(refer, false);
                String str = "";
                if (mFLive != null && mFLive.getLiveInfo() != null) {
                    str = mFLive.getLiveInfo().getLiveTitle();
                }
//                videoPlayer.setUp(url, false, str);
//                videoPlayer.startPlay();
                if (videoPlayer != null && isShouldMuteStart()) {
                    videoPlayer.setMute(true);
                } else {
                    if (isFromRoom) {
                        if (videoPlayer.isMute()) {
                            videoPlayer.setMute(false);
                        }
                    }
                }
                floatVideoUtils.play(refer, url, str, true);
                if (videoPlayer != null) {
                    videoPlayer.setShowLiveMode(isLiving);
                }
                isFirstPlay = false;
            }
        }, 80);
        isPlayFromRoom = isFromRoom;

    }

    private void freshVideoContain(int h) {
        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
        mlp.topMargin = topImg.getHeight() + layTitle.getHeight() + h;
        videoContainer.setLayoutParams(mlp);
    }

    private void msgHandler(Message msg) {
        if (msg.what == 1) {
//            JLog.e("scroll h="+scrollView.getHeight()+"\nimg    h="+img.getHeight()
//                    +"\nrecycl h="+recyclerView.getHeight());
//            appBarLayout.invalidate();
        }
    }

    /**
     * 切换直播间与聊天室的Tab的处理
     *
     * @param select
     * @param another
     */
    private void selectTab(CustomFontTextView select, CustomFontTextView another) {
        hasSelectRoom = true;
        Drawable d = getResources().getDrawable(R.color.colorHomeText);//ContextCompat.getDrawable(this, R.drawable.icon_bottom_line);
//        select.getCompoundDrawablePadding();
        d.setBounds(0, 0, select.getWidth(), DensityUtil.dip2px(this, 1));
        select.setCompoundDrawables(null, null, null, d);
        another.setCompoundDrawables(null, null, null, null);
        select.setTextColor(ContextCompat.getColor(this, R.color.blue_main));
        another.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
    }

    private Gson getGson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

//    private boolean isFirstInitInfo = true;

    /**
     * 初始化直播预告的内容
     *
     * @param fLive
     */
    private void initAdvanceInfo(FLive fLive) {
        if (fLive != null) {
            img.setVisibility(View.GONE);
            if (fLive.getLiveInfo() != null) {
                liveSource.setText("直播来源:" + fLive.getLiveInfo().getLiveSource());
                intro.setText("简介：" + fLive.getLiveInfo().getLiveIntro());
                date.setText(DateUtils.getDateDayString(DateUtils.getDataDate(fLive.getLiveInfo())));
                intro.setMovementMethod(ScrollingMovementMethod.getInstance());
            }
        }
    }

    /**
     * 初始化直播数据
     *
     * @param fLive
     * @return
     */
    private boolean initInfo(FLive fLive) {
        mFLive = fLive;
        if (mFLive == null) {
            img.setVisibility(View.GONE);
        } else {
//            fLive.getLiveInfo().
//            news24Domain
            if (fLive.getLiveInfo() != null) {
                getAttitudes(fLive.getLiveInfo().getLiveId());
                SkipUtil.skipToAddUserOperate(this, getOwnerName(), 1, 1, "直播阅读", fLive.getLiveInfo().getLiveId(), Cache.getInstance().getCurrentChannelId());
                if (!isAdvance) {
                    //TODO 启动直播在线统计
                    startOnlineService(handlerOnline);
                }
                //TODO 切换到调用服务器获取点击量
                initViewClickData(mFLive.getLiveInfo().getLiveId());
//                liveClickCount.setText("| 点击量：123");
                liveSource.setText("直播来源:" + mFLive.getLiveInfo().getLiveSource());
                intro.setText("简介：" + mFLive.getLiveInfo().getLiveIntro());
                intro.setMovementMethod(ScrollingMovementMethod.getInstance());
                date.setText(DateUtils.getDateDayString(DateUtils.getDataDate(mFLive.getLiveInfo())));
                handler.sendEmptyMessageDelayed(1, 300);
                livtTag.setVisibility(View.GONE);
//                livtTag.setVisibility(mFLive.getLiveInfo().isLiving() ? View.VISIBLE : View.GONE);
                liveUrl = mFLive.getLiveInfo().getLiveUrl();
                if (!TextUtils.isEmpty(liveUrl) && !isAdvance) {
                    if (NetUtils.isWifiConnected(this)) {
                        click(null);
                    }
                } else {
                    img.setVisibility(View.GONE);
                }

//            if (isFirstInitInfo){
//                isFirstInitInfo=false;
//                introToggle.setChecked(true);
//            }
                return true;
            }
        }
        return false;

//        if (mSelectedIndex == 0) {
//            liveRoomFragment.getData();
//        } else if (mSelectedIndex == 1) {
//            chatRoomFragment.getData();
//        }
    }

    /**
     * 增加点击
     *
     * @param liveID
     */
    private void initViewClickData(final String liveID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", liveID);
        p.put("type", 1);//type（0.新闻 1.直播)
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("", "" + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
                //增加点击量完成之后，获取点击量
                getLiveClickCount(liveID);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });


    }

    /**
     * 获取直播点击量
     *
     * @param liveID
     */
    private void getLiveClickCount(String liveID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", liveID);
        p.put("type", 1);//type（0.新闻 1.直播)
        NetUtils.getNetAdapter().getNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<NewsClickBean>(NewsClickBean.class) {
            @Override
            public void onSuc(NewsClickBean bean) {
                liveClickCount.setText(UIUtils.getNumber(bean.getViews()));
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    public void onClick(String imageUrl) {

    }

//    Handler handler1 = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg != null && msg.what == 111) {
//                sendmsg();
//            }
//        }
//    };
//    private Timer readyTimer;
//
//    public void startAdService(final Handler mHandler) {
//        try {
//            readyTimer = new Timer(true);
//            java.util.Date d1 = new java.util.Date();
//            readyTimer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    Message msg = new Message();
//                    msg.what = 111;
//                    mHandler.sendMessage(msg);
//                }
//            }, d1, 1000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private int count = 0;
//
//    private void sendmsg() {
//        if (videoPlayer != null && floatVideoUtils != null && floatVideoUtils.isHasInited()
//                && videoPlayer.canBarrage()) {
//            if (count % 3 == 1) {
//                videoPlayer.addMsg("张勇 =" + "测试弹幕显示长度超过一点限制了哦测试弹幕显示长度超过一点限制了哦测试弹幕显示长度超过一点限制了哦" + count);
//            } else if (count % 3 == 2) {
//                videoPlayer.addMsg("张勇 =" + "测试弹幕显示长度超过一点限制了哦测试弹幕显示长度超" + count);
//            } else {
//                videoPlayer.addMsg("张勇 =" + "测试弹 " + count);
//            }
//            count++;
//        }
//    }

    /**
     * 接受到推送的消息
     *
     * @param context
     * @param intent
     * @param object
     * @param isDynam
     */
    @Override
    public void onMsgRecieve(Context context, Intent intent, JSONObject object, boolean isDynam) {
        if (object == null) {
            return;
        }
        try {
            if (isDynam) {
                object = object.getJSONObject("data");
                if (object == null) {
                    return;
                }
                FLiveDy dynamic = getGson().fromJson(object.toString(), FLiveDy.class);
                if (liveRoomFragment != null) {
                    liveRoomFragment.addData(dynamic, 0);
                }
                if (videoPlayer != null && floatVideoUtils != null && floatVideoUtils.isHasInited()
                        && videoPlayer.canBarrage()) {
                    if (null != dynamic && !TextUtils.isEmpty(dynamic.getContentText())) {
                        videoPlayer.addMsg(getResources().getString(R.string.app_name)+"  =" + dynamic.getContentText());
                    }
                }

            } else {
                JSONArray ja = object.getJSONArray("data");
                if (ja == null || ja.length() == 0) {
                    return;
                }
                List<ChatItem> list = getGson().fromJson(ja.toString(), ListTypeUtils.ChatItem());
                if (chatRoomFragment != null && ListUtils.isListValued(list)) {
                    new ResultAsyncTask<Void>(list) {
                        @Override
                        protected Void doInBackground(Void... params) {
                            Collections.sort((List<ChatItem>) obj, new Comparator<ChatItem>() {
                                @Override
                                public int compare(ChatItem o1, ChatItem o2) {
                                    if (o1 != null && o2 != null) {
                                        Date date = DateUtils.getDataDate(o2);
                                        Date date1 = DateUtils.getDataDate(o1);
                                        int i = date.compareTo(date1);
                                        return i;
                                    }
                                    return 0;
                                }
                            });
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            if (chatRoomFragment != null) {
                                chatRoomFragment.addDatas((List<ChatItem>) obj, 0);
                            }
                        }
                    }.execute();

                }
                //shouldsetbarrage
                JLog.e("ppip  float=" + floatVideoUtils + "   " + floatVideoUtils.isHasInited() + "\n " + list + "\n" + videoPlayer + "\n" + videoPlayer.getFullWindowPlayer());
                if (videoPlayer != null && floatVideoUtils != null && floatVideoUtils.isHasInited()
                        && videoPlayer.canBarrage() && ListUtils.isListValued(list)) {
                    Comparator<ChatItem> comparator = new Comparator<ChatItem>() {
                        public int compare(ChatItem s1, ChatItem s2) {
                            long sL1 = DateUtils.paserStringDate(s1.getPubTime(), DateUtils.PATTERN_IN);
                            long sL2 = DateUtils.paserStringDate(s2.getPubTime(), DateUtils.PATTERN_IN);
                            // 先排年龄
                            if (sL1 != sL2) {
                                return (int) (sL1 - sL2);
                            } else {
                                return 0;
                            }
                        }
                    };
                    //这里就会自动根据规则进行排序
                    Collections.sort(list, comparator);
                    for (int i = 0; i < list.size(); i++) {
                        String str = list.get(i).getChatContent();
                        String nick = list.get(i).getUserName();
                        if (!TextUtils.isEmpty(str) && !TextUtils.isEmpty(nick)) {
                            videoPlayer.addMsg(nick + " =" + str);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class BarrageTestAsync extends ResultAsyncTask<Void> {
        private boolean canRun = true;

        @Override
        protected Void doInBackground(Void... params) {
            String[] strs = getResources().getStringArray(R.array.titlesss);
            while (canRun) {
                if (screenController != null) {
//					screenController.addMsg(strs[(int) (Math.random() * strs.length)]);
                }
                try {
                    Thread.sleep((long) (Math.random() * 10000L + 50));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        public void stop() {
            canRun = false;
        }
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    public String getCompere() {
        return mFLive.getLiveInfo().getLiveCompere();
    }

//    public String getChildUrl(int index) {
//        return mFLive == null || !ListUtils.isListValued(mFLive.getChannel()) ? "" : mFLive.getChannel().get(index).getChannelUrl();
//    }

    public void onNetFinish(boolean loadMoreEnabled) {
        mIsLoading = false;
//        if(!isFirstLoad) {
//            mRefreshLayout.refreshComplete();
//            mRefreshLayout.loadMoreComplete();
//        }
//        mRefreshLayout.setLoadMoreEnabled(loadMoreEnabled);
        MyJPushReceiver.setMsgRecieve(this);
    }

    @Override
    public void onSendComment() {
        if (TextUtils.isEmpty(baseConstUrl)) {
            showCommentDialog(mFLive.getLiveInfo().getLiveId(), null, Constances.COMMENT_TYPE_LIVE);
        } else {
            showCommentDialog(mFLive.getLiveInfo().getLiveId(), true, null, Constances.COMMENT_TYPE_LIVE);
        }
    }

    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(this.getClass().getName(), ex.toString());
        }
        return null;
    }

    /**
     * 获取本地已预约的直播数据
     *
     * @return
     */
    private List<FSubscribe> getDbListData() {
        try {
            List<FSubscribe> list = DBUtils.getInstance().findAll(FSubscribe.class);
            if (ListUtils.isListValued(list)) {
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setSubscribeList(LiveInfo subscribe) {
        FSubscribe s = new FSubscribe();
        s.setLiveId(subscribe.getLiveId());
        s.setLiveTime(subscribe.getLiveTime());
        s.setLiveTitle(subscribe.getLiveTitle());
        s.setSubscribe(true);
        DBUtils.getInstance().replaceAxync(s);
    }

    /**
     * 删除预约
     *
     * @param fSubscribe
     */
    private void deleteSubscribe(LiveInfo fSubscribe) {
        try {
            DBUtils.getInstance().getDbManager().deleteById(FSubscribe.class, fSubscribe.getLiveId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getDates(LiveInfo subscribe) {
        month = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "MM");
        day = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "dd");
        hour = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "HH");
        minute = DateUtils.getStringDate(DateUtils.getDataDate(subscribe), "mm");
        if (month.substring(0, 1).equals("0")) {
            month = month.substring(1, 2);
        }
        if (day.substring(0, 1).equals("0")) {
            day = day.substring(1, 2);
        }
        if (hour.substring(0, 1).equals("0")) {
            hour = hour.substring(1, 2);
        }
        if (minute.substring(0, 1).equals("0")) {
            minute = minute.substring(1, 2);
        }
    }

    /**
     * 设置闹钟定时通知提醒
     */
    private void setAlarm(String id, String title, String url, LiveInfo subscribe) {
        getDates(subscribe);
        int mon = Integer.parseInt(month) - 1;
        int da = Integer.parseInt(day);
        int hou = Integer.parseInt(hour);
        int min = Integer.parseInt(minute);
        final int AdvanceTime = 10;//设置提前十分钟发送消息
        java.sql.Date dataDate = DateUtils.getDataDate(subscribe);
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        long currentTimes = calendar.getTimeInMillis();
        long c = System.currentTimeMillis();
        if (dataDate != null) {
            long liveTime = dataDate.getTime() - AdvanceTime * 1000 * 60;
            if (currentTimes <= liveTime) {
                //如果减掉十分钟，时间依然比当前时间靠后，那么就减去十分钟定时，否则直接定时为开播时间。
                if (min < AdvanceTime) {
                    min = min + 60 - AdvanceTime;//设置提前十分钟发送消息
                    hou = hou - 1;
                } else {
                    min = min - AdvanceTime;
                }
            }
            liveTime = dataDate.getTime();
            if (currentTimes <= liveTime) {
                calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                calendar.set(Calendar.MONTH, mon);//从0开始，0表是1月，1表示2月依次类推
                calendar.set(Calendar.DAY_OF_MONTH, da);
                calendar.set(Calendar.HOUR_OF_DAY, hou);
                calendar.set(Calendar.MINUTE, min);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                long timeInMillis = calendar.getTimeInMillis();
                Intent intent = new Intent(RECEIVE_TAG);
                intent.putExtra(EX_ID, id);
                intent.putExtra(EX_TITLE, title);
                intent.putExtra(EX_URL, url);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, Integer.parseInt(id), intent, 0);
                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                //   am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1 * 1000, pendingIntent);//重复提醒
                am.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);

            } else {
                toast(R.string.living_over_time);
            }
        }

    }

    /**
     * 关闭定时通知提醒
     */
    private void stopAlarm(String id, String title, String url) {

        Intent intent = new Intent(RECEIVE_TAG);
        intent.putExtra(EX_ID, id);
        intent.putExtra(EX_TITLE, title);
        intent.putExtra(EX_URL, url);
        PendingIntent pi = PendingIntent.getBroadcast(this, Integer.parseInt(id),
                intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pi);
    }

    public SpannableStringBuilder setNumColor(String str) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        for (int i = 0; i < str.length(); i++) {
            char a = str.charAt(i);
            if (a >= '0' && a <= '9') {
                style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorTxRedMain)), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return style;
    }

    private void checkNotificationPermission() {
        boolean isNotification = NotificationsUtils.isNotificationEnabled(this);//NotificationManagerCompat.from(this).areNotificationsEnabled();
        if (!isNotification) {
            showDialog();
        }
        JLog.e("====notifi==" + isNotification);
    }

    public static final String SHOW_TAG = "dia_show_fragment";
    private ShowDiaFragment showDiaFragment;

    private void showDialog() {
        if (showDiaFragment == null) {
            showDiaFragment = new ShowDiaFragment();
        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.setType(2);
        showDiaFragment.show(getSupportFragmentManager(), SHOW_TAG);
    }

    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == ShowDiaFragment.NOTIFICATION_TAG) {
                toSetting();
            }
        }
    };

    private void toSetting() {
//        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS
//                , Uri.parse("package:" + getPackageName()));
//        startActivityForResult(intent, CheckPermission.SETTING_REQUEST);
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }


    /**************************直播在线日志统计******************************/


    Handler handlerOnline = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 22) {
                sendOnlineMsg();
            }
        }
    };
    private Timer readyOnlineTimer;
    private TimerTask RHTask;

    /**
     * 启动直播统计心跳
     *
     * @param mHandler
     */
    public void startOnlineService(final Handler mHandler) {
        if (null != mFLive && null != mFLive.getLiveInfo()) {
            long HeartbeatTime = 60 * 1000;//心跳时间
            try {
                readyOnlineTimer = new Timer(true);
                java.util.Date d1 = new java.util.Date();
                if (null == RHTask) {
                    RHTask = new TimerTask() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 22;
                            mHandler.sendMessage(msg);
                        }
                    };
                }
                readyOnlineTimer.schedule(RHTask, d1, HeartbeatTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向服务器发送日志
     */
    private void sendOnlineMsg() {
        if (null != mFLive && null != mFLive.getLiveInfo()) {
            SkipUtil.skipToAddOnline(this, getOwnerName(), mFLive.getLiveInfo().getLiveId(), 1);
        }
    }


    /****************************************************************************/
}
